﻿CREATE PROCEDURE [Mapping].[GenerateRuntimeView]
  @groupId int
AS
  IF NOT EXISTS (
    SELECT * FROM Mapping.MappingGroup
      WHERE [Id] = @groupId
        AND RuntimeViewHash = Mapping.GetRuntimeViewHash(@groupId)
  )
  BEGIN
    BEGIN TRY
      BEGIN TRAN
        DECLARE @viewName nvarchar(50)
        DECLARE @keyType nvarchar(20)
        SELECT @viewName = ISNULL(RuntimeView, 'vRt_' + GroupName),
            @keyType = ISNULL(AlternateKeyType, 'int')
          FROM Mapping.MappingGroup WHERE [Id] = @groupId

        DECLARE @sql nvarchar(MAX)

        SELECT @sql = Mapping.GetSQL_DropRuntimeView(@viewName)

        EXEC(@sql)

        SELECT @sql = Mapping.GetSQL_CreateRuntimeView(
          Mapping.GetSQL_SourceKeyOutput(@groupId),
          Mapping.GetSQL_SourceKeyPivot(@groupId),
          @keyType,
          @groupId,
          @viewName
        )

        EXEC(@sql)

        IF @@ERROR = 0
          UPDATE Mapping.MappingGroup SET RuntimeViewHash = Mapping.GetRuntimeViewHash(@groupId),
              RuntimeView = @viewName
            WHERE [Id] = @groupId
      COMMIT
    END TRY
    BEGIN CATCH
      IF @@TRANCOUNT > 0 ROLLBACK
    END CATCH
  END
RETURN @@ERROR
